//
//  FuelLogAppDelegate.m
//  FuelLog
//
//  Created by Pure Mass Communications on 9/1/08.
//  Copyright  2008. All rights reserved.
//
//  Placed under GPL v2 with the kind permission of Pure Mass Communications
//
//  Modified to make compile under SDK 3.1 by Olaf Greck in May 2010
//
//
//  This program is free software; you can redistribute it and/or
//  modify it under the terms of the GNU General Public License
//  as published by the Free Software Foundation; either version 2
//  of the License, or (at your option) any later version.

//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.

//  You should have received a copy of the GNU General Public License
//  along with this program; if not, write to the Free Software
//  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

#import "GasCell.h"
#import "FuelLogViewController.h"
#import "FuelLogAppDelegate.h"

#define ROW_HEIGHT 60

static AddCarViewController *__addCarViewController = nil;
static DateViewController *__dateViewController = nil;
static LoginViewController *__loginViewController = nil;
static FilesViewController *__filesViewController = nil;

@implementation FuelLogViewController

+ (AddCarViewController *)addCarViewController {
	if (__addCarViewController == nil) {
		__addCarViewController = [[AddCarViewController alloc] initWithNibName:@"AddCar" bundle:nil];
	}
	return __addCarViewController;
}

+ (LoginViewController *)loginViewController {
	if (__loginViewController == nil) {
		__loginViewController = [[LoginViewController alloc] initWithNibName:@"Login" bundle:nil];
	}
	return __loginViewController;
}

+ (FilesViewController *)filesViewController {
	if (__filesViewController == nil) {
		__filesViewController = [[FilesViewController alloc] initWithNibName:@"Files" bundle:nil];
	}
	return __filesViewController;
}

+ (DateViewController *)dateViewController {
	if (__dateViewController == nil) {
		__dateViewController = [[DateViewController alloc] initWithNibName:@"Date" bundle:nil];
	}
	return __dateViewController;
}

+ (void)staticCleanUp {
	if (__addCarViewController) {
		[__addCarViewController dealloc];
		__addCarViewController = nil;
	}
	if (__dateViewController) {
		[__dateViewController dealloc];
		__dateViewController = nil;
	}
}

/*
- (void)loadView {
}
 */


/*
- (void)viewDidLoad {
}
*/

- (void)viewWillAppear:(BOOL)animated {
    [tableView reloadData];
	[super setEditing:YES animated:NO];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
	// Return YES for supported orientations
	return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


- (void)didReceiveMemoryWarning {
	[super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
	// Release anything that's not essential, such as cached data
}


- (void)dealloc {
	if (carsController) [carsController dealloc];
	if (gasController) [gasController dealloc];
	if (statsController) [statsController dealloc];
	if (prefsController) [prefsController dealloc];
	[super dealloc];
}

- (IBAction)addCar:(id)sender {
	if (carsController == nil) {
		carsController = [[CarsViewController alloc] initWithNibName:@"Cars" bundle:nil];
	}
	[self presentModalViewController:carsController animated:YES];
}

- (IBAction)addGas:(id)sender {
	if (gasController == nil) {
		gasController = [[GasViewController alloc] initWithNibName:@"Gas" bundle:nil];
	}
	FuelLogAppDelegate *appDelegate = (FuelLogAppDelegate *)[[UIApplication sharedApplication] delegate];
	Gas *gas = [[Gas alloc] init:appDelegate.currentCar];
	[gasController setGas:gas];
	[gasController setBoxes];
	[self presentModalViewController:gasController animated:YES];
}

- (IBAction)viewStats:(id)sender {
	if (statsController == nil) {
		statsController = [[StatsViewController alloc] initWithNibName:@"Stats" bundle:nil];
	}
	[self presentModalViewController:statsController animated:YES];
}

- (IBAction)setPrefs:(id)sender {
	if (prefsController == nil) {
		prefsController = [[PrefsViewController alloc] initWithNibName:@"Prefs" bundle:nil];
	}
	[self presentModalViewController:prefsController animated:YES];
}

#pragma mark Table section

- (NSInteger)numberOfSectionsInTableView:(UITableView *)aTableView {
	// each year is a section
	FuelLogAppDelegate *appDelegate = (FuelLogAppDelegate *)[[UIApplication sharedApplication] delegate];
	if (appDelegate.pumps.count > 0) {
		return appDelegate.sections.count;
	} 
	return 1;
}

- (NSInteger)tableView:(UITableView *)aTableView numberOfRowsInSection:(NSInteger)section {
	FuelLogAppDelegate *appDelegate = (FuelLogAppDelegate *)[[UIApplication sharedApplication] delegate];
	if (appDelegate.pumps.count > 0) {
		if (section == appDelegate.sections.count - 1) {
			// add empty row to make scroll easier.
			return appDelegate.pumps.count - [(NSNumber *)[appDelegate.sections objectAtIndex:section] intValue] + 1;
		} else {
			return 
				[(NSNumber *)[appDelegate.sections objectAtIndex:section+1] intValue] - 
				[(NSNumber *)[appDelegate.sections objectAtIndex:section] intValue];
		}
	} 
	return appDelegate.pumps.count;
}

- (NSString *)tableView:(UITableView *)aTableView titleForHeaderInSection:(NSInteger)section {
	FuelLogAppDelegate *appDelegate = (FuelLogAppDelegate *)[[UIApplication sharedApplication] delegate];
	NSCalendar *cal = [NSCalendar currentCalendar];
	if (appDelegate.pumps.count > 0) {
		NSCalendar *cal = [NSCalendar currentCalendar];
		int idx = [(NSNumber *)[appDelegate.sections objectAtIndex:section] intValue];
		int year = [[cal components:NSYearCalendarUnit fromDate:((Gas *)[appDelegate.pumps objectAtIndex:idx]).date] year];
		return [NSString stringWithFormat:@"%d (%@)", year, appDelegate.currentCar.label];
	}
	int y = [[cal components:NSYearCalendarUnit fromDate:[NSDate date]] year];
	return [NSString stringWithFormat:@"%d (%@)", y, appDelegate.currentCar.label];
}

// /*
- (UITableViewCellAccessoryType)tableView:(UITableView *)tv accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {
    FuelLogAppDelegate *appDelegate = (FuelLogAppDelegate *)[[UIApplication sharedApplication] delegate];
	int row = indexPath.row + [(NSNumber *)[appDelegate.sections objectAtIndex:indexPath.section] intValue];
	if (row == appDelegate.pumps.count) {
		return UITableViewCellAccessoryNone;
	}
    return UITableViewCellAccessoryDetailDisclosureButton;
}

// */

- (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath {	
	static NSString *CellIdentifier = @"GasCell";	
	GasCell *gasCell = (GasCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	if (gasCell == nil) {
		CGRect startingRect = CGRectMake(0.0, 0.0, 320.0, ROW_HEIGHT);
		gasCell = [[[GasCell alloc] initWithFrame:startingRect // reuseIdentifier:CellIdentifier
					] autorelease];
	}
    FuelLogAppDelegate *appDelegate = (FuelLogAppDelegate *)[[UIApplication sharedApplication] delegate];
	int row = indexPath.row + [(NSNumber *)[appDelegate.sections objectAtIndex:indexPath.section] intValue];
	if (row == appDelegate.pumps.count) {
		[gasCell setGas:nil];
#pragma mark FIXME accessoryType
		// gasCell.accessoryType = UITableViewCellAccessoryNone;
	} else {
		[gasCell setGas:[appDelegate.pumps objectAtIndex:row]];
	}
	return gasCell;
}

- (void)tableView:(UITableView *)aTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	/*
	 To conform to the Human Interface Guidelines, selections should not be persistent --
	 deselect the row after it has been selected.
	 */
	[aTableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath {
	if (gasController == nil) {
		gasController = [[GasViewController alloc] initWithNibName:@"Gas" bundle:nil];
	}
    FuelLogAppDelegate *appDelegate = (FuelLogAppDelegate *)[[UIApplication sharedApplication] delegate];
	int row = indexPath.row + [(NSNumber *)[appDelegate.sections objectAtIndex:indexPath.section] intValue];
	if (row == appDelegate.pumps.count) {
		return;
	}
	Gas *gas = [appDelegate.pumps objectAtIndex:row];
	[gas retain];
	[gasController setGas:gas];
	[gasController setBoxes];
	[self presentModalViewController:gasController animated:YES];
}

@end
